# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import random

import math
from django.db.models import Sum
from django.shortcuts import HttpResponse
from django.shortcuts import render

from bigscreen import tasks
from bigscreen.models import StationOrders
from cache_manager import RedisHelper


def screen(request):
    return render(request, "screen/bigscreen.html")


def station_data(request):
    # stations = RedisHelper().get__all__map('paygather:STATION_POINT_KEY')
    stations = StationOrders.objects.all()
    geo_coord_map = dict()
    for station in stations:
        # station = json.loads(stations[Id])
        geo_coord_map[station.station_name] = [station.station_longitude, station.station_latitude]
    return HttpResponse(json.dumps(geo_coord_map, ensure_ascii=False))


def order_data(request):
    # stations = RedisHelper().get__all__map('paygather:STATION_POINT_KEY')
    stations = StationOrders.objects.filter(station_num__gt=20)
    station_order = []
    for station in stations:
        station_order.append({
            "name": station.station_name,
            "value": station.station_num
        })

    return HttpResponse(json.dumps(station_order, ensure_ascii=False))


def order_avg(request):
    orders_num = StationOrders.objects.raw(
        "SELECT id,SUM(station_num) AS all_orders FROM bigscreen_stationorders WHERE station_num>=20")[0].all_orders
    if orders_num is None:
        orders_num = 0
    station_num = StationOrders.objects.filter(station_num__gt=20).count()
    order_avg = 1
    if station_num != 0:
        order_avg = math.ceil(orders_num / station_num)
    return HttpResponse(order_avg)


def init_info(request):
    # res = tasks.add()
    # print("start running task")
    # print("async task res", res)
    stations = RedisHelper().get__all__map('paygather:STATION_POINT_KEY')
    result = ''
    for Id in stations:
        station = json.loads(stations[Id])
        try:
            StationOrders.objects.get(station_id=Id)
        except StationOrders.DoesNotExist:
            result += station['stationName'] + ";"
            StationOrders.objects.create(station_id=Id, station_name=station['stationName'],
                                         station_longitude=station.get('longitude', 0.00), station_latitude=
                                         station.get('latitude', 0.00), station_num=0)
    return HttpResponse('信息初始化成功,新增:' + result)
